﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using Flickr2Frame;
using FlickrNet;

namespace Configure_Frame
{
    public partial class ConfigFrame : Form
    {
        const string flickr2FrameXmlName = "Flickr2Frame.xml";
        const string setNamePrefix = "Flickr2Frame";
        const string applicationDirectory = "Flickr2Frame";
        const string setNameDelimiter = "_";
        const string sampleSetLabel = "Homer";
        const string sampleAccountType = "Free";
        const string sampleDownloadSize = "Large";
        const string sampleUserId = "41095231@N04";
        const string sampleAPIKey = "2905f526d18f3b6ac645fd1cec20cbeb";
        const string sampleAuthenticationToken = "72157621946890824-63069f1f52934f20";
        const string sampleSharedSecret = "7939f0e5dc969cbe";

        ErrorProvider errorProvider = new ErrorProvider();
        string[] applicationFiles = { "Flickr2Frame.exe", "FlickrNet.dll", "ConfigFrame.exe", "Interop.IWshRuntimeLibrary.dll" };

        public ConfigFrame()
        {
            InitializeComponent();
            this.Text += String.Format(" ({0}.{1}.{2})", Assembly.GetExecutingAssembly().GetName().Version.Major, Assembly.GetExecutingAssembly().GetName().Version.Minor, Assembly.GetExecutingAssembly().GetName().Version.Build);
            this.Load += new EventHandler(ConfigFrame_Load);
            selectDriveButton.Click += new EventHandler(selectDriveButton_Click);
            sampleButton.Click += new EventHandler(sampleButton_Click);
            saveButton.Click += new EventHandler(saveButton_Click);
            canButton.Click += new EventHandler(canButton_Click);
            testButton.Click += new EventHandler(testButton_Click);
            driveLetterLabel.TextChanged += new EventHandler(driveLetterLabel_TextChanged);
            homeLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.homeLinkLabel_LinkClicked);
            accountTypeComboBox.SelectedIndexChanged += new EventHandler(accountTypeComboBox_SelectedIndexChanged);
        }

        void testButton_Click(object sender, EventArgs e)
        {
            if (ValidateFormData())
            {
                SetFormState(false);
                TestFlickrAPIDetails(userIdTextBox.Text, apiKeyTextBox.Text, authTokenTextBox.Text, sharedSecretTextBox.Text);
                SetFormState(true);
            }
        }

        void TestFlickrAPIDetails(string userID, string apiKey, string authToken, string sharedSecret)
        {
            try
            {
                Flickr flickr = new Flickr(apiKey, sharedSecret, authToken);
                Person person = flickr.PeopleGetInfo(userID);
                MessageBox.Show("Successfully connected to Flickr using the API details provided.", "Flickr API Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Flickr API Test", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void accountTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (accountTypeComboBox.SelectedIndex != -1)
            {
                downloadSizeComboBox.Items.Clear();

                switch (accountTypeComboBox.SelectedItem.ToString())
                {
                    case "Free":
                        downloadSizeComboBox.Items.Add("Small");
                        downloadSizeComboBox.Items.Add("Medium");
                        downloadSizeComboBox.Items.Add("Large");
                        break;
                    case "Pro":
                        downloadSizeComboBox.Items.Add("Small");
                        downloadSizeComboBox.Items.Add("Medium");
                        downloadSizeComboBox.Items.Add("Original");
                        break;
                }
            }
        }

        void ConfigFrame_Load(object sender, EventArgs e)
        {
            try
            {
                if (RunningFromFrame())
                {
                    driveLetterLabel.Text = Assembly.GetExecutingAssembly().Location.Substring(0, 3);
                }
                else
                {
                    selectDriveButton.PerformClick();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ConfigFrame_Load()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void driveLetterLabel_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (driveLetterLabel.Text != null)
                {
                    ReadConfigXml(Path.Combine(driveLetterLabel.Text, flickr2FrameXmlName));
                    photoDirectoryComboBox.Items.Clear();
                    photoDirectoryComboBox.Sorted = true;

                    try
                    {
                        foreach (string dir in Directory.GetDirectories(driveLetterLabel.Text))
                        {
                            photoDirectoryComboBox.Items.Add(new DirectoryInfo(dir).Name);
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "driveLetterLabel_TextChanged()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void canButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void saveButton_Click(object sender, EventArgs e)
        {
            errorProvider.Dispose();

            if (ValidateFormData())
            {
                SetFormState(false);

                if (ValidateFrame() && SaveConfigFile() && CopyApplicationToFrame() && ConfigureAutorun())
                {
                    MessageBox.Show("Flickr2Frame is now configured to download photos on to your frame from Flickr.\r\rThe Flickr2Frame application has also been copied on to the frame, and configured to automatically launch when the frame is connected to a PC.", "Flickr2Frame Configuration Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                else
                {
                    SetFormState(true);
                }
            }
        }

        void SetFormState(bool enabled)
        {
            testButton.Enabled = enabled;
            saveButton.Enabled = enabled;
            canButton.Enabled = enabled;
            frameGroupBox.Enabled = enabled;
            flickrGroupBox.Enabled = enabled;
            this.Refresh();
        }

        void sampleButton_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult useSample = MessageBox.Show("This option allows you to use working sample information, which will download photos from the Flickr2Frame profile on Flickr.\r\rThis enables you to test the application without opening a Flickr account of your own, or going through any of the initial setup tasks. If you like what you see, you can replace the information with you own account details, and start using Flickr2Frame for real.\r\rWould you like to use the sample information?", "Use Flickr2Frame Profile?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (useSample == DialogResult.Yes)
                {
                    setLabelTextBox.Text = sampleSetLabel;
                    SelectValueInComboBox(ref accountTypeComboBox, sampleAccountType);
                    SelectValueInComboBox(ref downloadSizeComboBox, sampleDownloadSize);
                    userIdTextBox.Text = sampleUserId;
                    apiKeyTextBox.Text = sampleAPIKey;
                    authTokenTextBox.Text = sampleAuthenticationToken;
                    sharedSecretTextBox.Text = sampleSharedSecret;
                    MessageBox.Show("These settings will download photos for \"" + sampleSetLabel + "\" from the Flickr2Frame profile on Flickr.\r\rThe following Sets are available:\r\r\t" + String.Format("{0}{1}{2}{1}{3}", setNamePrefix, setNameDelimiter, sampleSetLabel, "Animals") + "\r\t" + String.Format("{0}{1}{2}{1}{3}", setNamePrefix, setNameDelimiter, sampleSetLabel, "Buildings") + "\r\t" + String.Format("{0}{1}{2}{1}{3}", setNamePrefix, setNameDelimiter, sampleSetLabel, "Landscapes") + "\r\rFeel free to experiment with different download sizes.", "Flickr2Frame Profile In Use", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "sampleButton_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void selectDriveButton_Click(object sender, EventArgs e)
        {
            try
            {
                DriveSelector ds = new DriveSelector();

                if (ds.ShowDialog() == DialogResult.OK)
                {
                    driveLetterLabel.Text = ds.SelectedDriveLetter + @"\";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "selectDriveButton_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void ReadConfigXml(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    XmlDocument configXml = new XmlDocument();
                    StringEncryption se = new StringEncryption();
                    configXml.Load(path);

                    try
                    {
                        SelectValueInComboBox(ref frameTypeComboBox, configXml.SelectSingleNode("configuration/frame_type").InnerText);
                    }
                    catch
                    {
                    }

                    try
                    {
                        photoDirectoryComboBox.Text = configXml.SelectSingleNode("configuration/photo_directory").InnerText;
                    }
                    catch
                    {
                    }

                    try
                    {
                        SelectValueInComboBox(ref photoOrderComboBox, configXml.SelectSingleNode("configuration/photo_order").InnerText);
                    }
                    catch
                    {
                    }

                    try
                    {
                        setLabelTextBox.Text = configXml.SelectSingleNode("configuration/flickr_set_prefix").InnerText;
                    }
                    catch
                    {
                    }

                    try
                    {
                        SelectValueInComboBox(ref accountTypeComboBox, configXml.SelectSingleNode("configuration/flickr_account_type").InnerText);
                    }
                    catch
                    {
                    }

                    try
                    {
                        SelectValueInComboBox(ref downloadSizeComboBox, configXml.SelectSingleNode("configuration/photo_download_size").InnerText);
                    }
                    catch
                    {
                    }

                    try
                    {
                        userIdTextBox.Text = se.Decrypt(configXml.SelectSingleNode("configuration/flickr_user_id").InnerText, "charlton");
                    }
                    catch
                    {
                    }

                    try
                    {
                        apiKeyTextBox.Text = se.Decrypt(configXml.SelectSingleNode("configuration/flickr_api_key").InnerText, "charlton");
                    }
                    catch
                    {
                    }

                    try
                    {
                        authTokenTextBox.Text = se.Decrypt(configXml.SelectSingleNode("configuration/flickr_authentication_token").InnerText, "charlton");
                    }
                    catch
                    {
                    }

                    try
                    {
                        sharedSecretTextBox.Text = se.Decrypt(configXml.SelectSingleNode("configuration/flickr_shared_secret").InnerText, "charlton");
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ReadConfigXml()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void SelectValueInComboBox(ref ComboBox combobox, string value)
        {
            try
            {
                if (combobox.Items.Count > 0)
                {
                    for (int i = 0; i < combobox.Items.Count; i++)
                    {
                        if (String.Compare(combobox.Items[i].ToString(), value, true) == 0)
                        {
                            combobox.SelectedIndex = i;
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SelectValueInComboBox()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void homeLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "http://flickr2frame.codeplex.com/";
                p.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "homeLinkLabel_LinkClicked()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        bool ValidateFormData()
        {
            try
            {
                if (driveLetterLabel.Text.Trim().Length == 0)
                {
                    errorProvider.SetError(driveLetterLabel, "Please select the drive letter that represents your phtos frame.");
                    return false;
                }

                if (frameTypeComboBox.SelectedIndex == -1)
                {
                    errorProvider.SetError(frameTypeComboBox, "Please choose a frame type (if in doubt, select GenericUSB01).");
                    frameTypeComboBox.Select();
                    frameTypeComboBox.DroppedDown = true;
                    return false;
                }

                if ((photoDirectoryComboBox.SelectedIndex == -1) && (photoDirectoryComboBox.Text.Trim().Length == 0))
                {
                    errorProvider.SetError(photoDirectoryComboBox, "Please specify a directory on the frame where photos should be saved.");
                    photoDirectoryComboBox.Select();
                    photoDirectoryComboBox.DroppedDown = true;
                    return false;
                }

                if (photoOrderComboBox.SelectedIndex == -1)
                {
                    errorProvider.SetError(photoOrderComboBox, "Please select the order in which you would like to save photos.");
                    photoOrderComboBox.Select();
                    photoOrderComboBox.DroppedDown = true;
                    return false;
                }

                if (setLabelTextBox.Text.Trim().Length == 0)
                {
                    errorProvider.SetError(setLabelTextBox, "Please specify the set label.\r\rExample: \"" + sampleSetLabel + "\" = \"" + String.Format("{0}{1}{2}{1}{3}", setNamePrefix, setNameDelimiter, sampleSetLabel, "Some Album") + "\"");
                    setLabelTextBox.Select();
                    return false;
                }

                if (accountTypeComboBox.SelectedIndex == -1)
                {
                    errorProvider.SetError(accountTypeComboBox, "Please select which type of Flickr account you have.");
                    accountTypeComboBox.Select();
                    accountTypeComboBox.DroppedDown = true;
                    return false;
                }

                if (downloadSizeComboBox.SelectedIndex == -1)
                {
                    errorProvider.SetError(downloadSizeComboBox, "Please select which photo size you would like to download.");
                    downloadSizeComboBox.Select();
                    downloadSizeComboBox.DroppedDown = true;
                    return false;
                }

                if (userIdTextBox.Text.Trim().Length == 0)
                {
                    errorProvider.SetError(userIdTextBox, "Please specify your Flickr username (API, not login).");
                    userIdTextBox.Select();
                    return false;
                }

                if (apiKeyTextBox.Text.Trim().Length == 0)
                {
                    errorProvider.SetError(apiKeyTextBox, "Please specify your Flickr API Key.");
                    apiKeyTextBox.Select();
                    return false;
                }

                if (authTokenTextBox.Text.Trim().Length == 0)
                {
                    errorProvider.SetError(authTokenTextBox, "Please specify your Flickr Authentication Token.");
                    authTokenTextBox.Select();
                    return false;
                }

                if (sharedSecretTextBox.Text.Trim().Length == 0)
                {
                    errorProvider.SetError(sharedSecretTextBox, "Please specify your Flickr Shared Secret.");
                    sharedSecretTextBox.Select();
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ValidateFormData()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return true;
        }

        bool ValidateFrame()
        {
            try
            {
                string albumPath = null;

                try
                {
                    albumPath = Path.Combine(driveLetterLabel.Text, photoDirectoryComboBox.Text);
                }
                catch (Exception ex)
                {
                    errorProvider.SetError(photoDirectoryComboBox, ex.Message);
                    return false;
                }

                if (!Directory.Exists(driveLetterLabel.Text))
                {
                    errorProvider.SetError(driveLetterLabel, "This drive no longer exists.");
                    return false;
                }

                if (!Directory.Exists(albumPath))
                {
                    DialogResult createDirectory = MessageBox.Show("\"" + albumPath + "\" does not currently exist.\r\rWould you like to create this directory now?", "Create Photo Directory", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (createDirectory == DialogResult.Yes)
                    {
                        try
                        {
                            Directory.CreateDirectory(albumPath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Error Creating Directory", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    DialogResult disclaimer = MessageBox.Show("All files and folders in the following directory will be deleted when Flickr2Frame performs an update:\r\r\t" + albumPath + "\r\rAre you sure you want to download photos to this directory?\r\rPLEASE ENSURE ALL FILES IN " + albumPath + " HAVE BEEN BACKED UP PRIOR TO RUNNING FLICKR2FRAME.", "Disclaimer", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (disclaimer != DialogResult.Yes)
                    {
                        return false;
                    }
                }

                if (!Directory.Exists(albumPath))
                {
                    errorProvider.SetError(photoDirectoryComboBox, "This directory does not exist.");
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ValidateFrame()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return true;
        }

        bool SaveConfigFile()
        {
            try
            {
                XmlDocument configXml = new XmlDocument();
                XmlNode node;
                StringEncryption se = new StringEncryption();
                string xmlPath = Path.Combine(driveLetterLabel.Text, flickr2FrameXmlName);
                configXml.LoadXml("<configuration />");
                configXml.InsertBefore(configXml.CreateComment("http://www.flickr2frame.com/"), configXml.DocumentElement);
                configXml.InsertBefore(configXml.CreateComment("Use the ConfigFrame.exe application to edit this file, some values are encrypted."), configXml.DocumentElement);
                node = configXml.CreateElement("frame_type");
                node.InnerText = frameTypeComboBox.SelectedItem.ToString();
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("photo_directory");
                node.InnerText = photoDirectoryComboBox.Text;
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("photo_order");
                node.InnerText = photoOrderComboBox.SelectedItem.ToString();
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("photo_download_size");
                node.InnerText = downloadSizeComboBox.SelectedItem.ToString();
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("flickr_account_type");
                node.InnerText = accountTypeComboBox.SelectedItem.ToString();
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("flickr_set_prefix");
                node.InnerText = setLabelTextBox.Text;
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("flickr_user_id");
                node.InnerText = se.Encrypt(userIdTextBox.Text, "charlton");
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("flickr_api_key");
                node.InnerText = se.Encrypt(apiKeyTextBox.Text, "charlton");
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("flickr_shared_secret");
                node.InnerText = se.Encrypt(sharedSecretTextBox.Text, "charlton");
                configXml.DocumentElement.AppendChild(node);
                node = configXml.CreateElement("flickr_authentication_token");
                node.InnerText = se.Encrypt(authTokenTextBox.Text, "charlton");
                configXml.DocumentElement.AppendChild(node);
                configXml.Save(xmlPath);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SaveConfigFile()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }

        bool CopyApplicationToFrame()
        {
            try
            {
                if (!RunningFromFrame())
                {
                    if (FilesExist(applicationFiles, AppDomain.CurrentDomain.BaseDirectory))
                    {
                        Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                        string framePath = Path.Combine(driveLetterLabel.Text, applicationDirectory);

                        if (!Directory.Exists(framePath))
                        {
                            Directory.CreateDirectory(framePath);
                        }

                        foreach (string file in applicationFiles)
                        {
                            File.Copy(file, Path.Combine(framePath, file), true);
                        }

                        UpgradeAppConfigFile("Flickr2Frame.exe.config", Path.Combine(framePath, "Flickr2Frame.exe.config"));
                    }
                    else
                    {
                        string fileList = null;

                        foreach (string file in applicationFiles)
                        {
                            fileList += "\r\t" + file;
                        }

                        MessageBox.Show("Some Flickr2Frame files are missing.\r\r Please ensure the following files are present in the same directory as ConfigFrame.exe:\r" + fileList, "Missing Files", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "CopyApplicationToFrame()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }

        bool ConfigureAutorun()
        {
            try
            {
                StreamWriter autorun = new StreamWriter(Path.Combine(driveLetterLabel.Text, "autorun.inf"), false);
                autorun.WriteLine(@"[autorun]");
                autorun.WriteLine(@"open=Flickr2Frame\Flickr2Frame.exe");
                //autorun.WriteLine(@"icon=Flickr2Frame\Flickr2Frame.exe,0");
                autorun.WriteLine(@"action=Update your photo frame with Flickr2Frame");
                autorun.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ConfigureAutorun()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }

        bool RunningFromFrame()
        {
            try
            {
                FileInfo me = new FileInfo(Assembly.GetExecutingAssembly().Location);

                if (String.Compare(String.Format(@":\{0}\{1}", applicationDirectory, me.Name), String.Format(@":\{0}\{1}", me.Directory.Name, me.Name)) == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "RunningFromFrame()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }

        bool FilesExist(string[] files, string currentDirectory)
        {
            try
            {
                Environment.CurrentDirectory = currentDirectory;

                if (files != null)
                {
                    foreach (string file in files)
                    {
                        if (!File.Exists(file))
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "FilesExist()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }

        void UpgradeAppConfigFile(string newFilePath, string targetFilePath)
        {
            try
            {
                if (File.Exists(newFilePath))
                {
                    if (File.Exists(targetFilePath))
                    {
                        string tempFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
                        string tempConfigPath = Path.Combine(tempFolder, new FileInfo(targetFilePath).Name);
                        File.Copy(targetFilePath, tempConfigPath, true);
                        File.Copy(newFilePath, targetFilePath, true);
                        XmlDocument newConfig = new XmlDocument();
                        newConfig.Load(targetFilePath);
                        XmlDocument oldConfig = new XmlDocument();
                        oldConfig.Load(tempConfigPath);

                        foreach (XmlNode n in oldConfig.SelectNodes("configuration/appSettings/add"))
                        {
                            //if (newConfig.SelectSingleNode("configuration/appSettings/add[@key=\"" + n.Attributes.GetNamedItem("key").Value + "\"]") == null)
                            //{
                            //    if (n.PreviousSibling.Name == "#comment")
                            //    {
                            //        newConfig.SelectSingleNode("configuration/appSettings").AppendChild(newConfig.ImportNode(n.PreviousSibling, false));
                            //    }

                            //    newConfig.SelectSingleNode("configuration/appSettings").AppendChild(newConfig.ImportNode(n, false));
                            //}
                            //else
                            //{
                            //    newConfig.SelectSingleNode("configuration/appSettings/add[@key=\"" + n.Attributes.GetNamedItem("key").Value + "\"]").Attributes.GetNamedItem("value").Value = n.Attributes.GetNamedItem("value").Value;
                            //}

                            if (newConfig.SelectSingleNode("configuration/appSettings/add[@key=\"" + n.Attributes.GetNamedItem("key").Value + "\"]") != null)
                            {
                                newConfig.SelectSingleNode("configuration/appSettings/add[@key=\"" + n.Attributes.GetNamedItem("key").Value + "\"]").Attributes.GetNamedItem("value").Value = n.Attributes.GetNamedItem("value").Value;
                            }
                        }

                        newConfig.Save(targetFilePath);
                    }
                    else
                    {
                        File.Copy(newFilePath, targetFilePath, true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "UpgradeAppConfigFile()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
